//
//  HUnUploadViewController.m
//  NursingManages
//
//  Created by Zhen Huang on 17/6/8.
//  Copyright © 2017年 huangzhen. All rights reserved.
//

#import "HUnUploadViewController.h"
#import "HUploadBaseTableViewCell.h"
#import "InitDbTableQuality.h"
#import "HQc_codeModel.h"
#import "HCommon.h"
#import "Model_Hr_Ns_Inspect_New.h"
#import "HQCSpecificViewController.h"
#import "HSavedEditViewController.h"
#import "InitDbTable.h"
#import "HNightHistoryTableViewCell.h"
#import "HNightHistoryEditViewController.h"
#import "TablePubDictionaryItem.h"
@interface HUnUploadViewController ()
<UITableViewDelegate,
UITableViewDataSource>
@property (nonatomic ,strong) UITableView *tableview;
@property (nonatomic ,strong) NSMutableArray *dataArray;
@property (nonatomic ,strong) NSMutableArray *rowOfSectionArray;
@property (nonatomic ,strong) NSMutableArray *codeArray;
@property (nonatomic ,strong) NSMutableArray *titleArray;
@property (nonatomic ,assign) NSInteger type;
@property (nonatomic ,assign) NSInteger indexSection;
@property (nonatomic ,assign) NSInteger indexRow;
@property (nonatomic ,strong) NSIndexPath *indexPath;
@property (nonatomic ,copy) NSString *level_id;
@property (nonatomic ,strong) NSDictionary *param;
@property (nonatomic ,assign) NSInteger isHNight;
@property (nonatomic ,copy) NSString *modelItem;
@property (nonatomic ,copy) NSString *dept_name;
@end

@implementation HUnUploadViewController

- (instancetype)initWithType:(NSInteger )type
                    level_id:(NSString *)level_id
                       param:(NSDictionary *)param
                    isHNight:(NSInteger)isHNight
{
    if (self) {
        self.dataArray = [NSMutableArray new];
        self.codeArray = [NSMutableArray new];
        self.titleArray = [NSMutableArray new];
        self.type = type;
        self.level_id = level_id;
        self.param = param;
        self.isHNight = isHNight;
        self.rowOfSectionArray = [NSMutableArray new];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableview];
    InitDbTableQuality *initd = [[InitDbTableQuality alloc]init];
    if (self.type == 1) {
        self.dataArray = [initd GetMainTableWithUpload_flag:0 typy_id:[self.param objectForKey:@"TYPE_ID"]level_id:self.level_id];
    }else if (self.type == 2)
    {
        self.dataArray = [initd GetMainTableWithUpload_flag:1 typy_id:[self.param objectForKey:@"TYPE_ID"]level_id:self.level_id];
    }
    [self GetData];
    
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(RefreshNotice:) name:@"Refresh" object:nil];
    
    NSNotificationCenter * centerSuccess = [NSNotificationCenter defaultCenter];
    [centerSuccess addObserver:self selector:@selector(RefreshNoticeSuccess:) name:@"uploadSuccess" object:nil];

    NSNotificationCenter * centerHnight = [NSNotificationCenter defaultCenter];
    [centerHnight addObserver:self selector:@selector(RefreshNoticeHnight:) name:@"HNightRefresh" object:nil];
    

}
#pragma 通知的事件,执行刷新
- (void)RefreshNotice:(NSNotification *)sender
{
    [self.dataArray removeAllObjects];
    [self.titleArray removeAllObjects];
    InitDbTableQuality *initd = [[InitDbTableQuality alloc]init];
    if (self.type == 1) {
        self.dataArray = [initd GetMainTableWithUpload_flag:0 typy_id:[self.param objectForKey:@"TYPE_ID"]level_id:self.level_id];
    }else if (self.type == 2)
    {
        self.dataArray = [initd GetMainTableWithUpload_flag:1 typy_id:[self.param objectForKey:@"TYPE_ID"]level_id:self.level_id];
    }
    [self GetData];

    [self.tableview reloadData];
}
#pragma 通知的事件,执行刷新(上传成功)

- (void)RefreshNoticeSuccess:(NSNotification *)sender
{
    [self.dataArray removeAllObjects];
    [self.titleArray removeAllObjects];
    InitDbTableQuality *initd = [[InitDbTableQuality alloc]init];
    if (self.type == 1) {
        self.dataArray = [initd GetMainTableWithUpload_flag:0 typy_id:[self.param objectForKey:@"TYPE_ID"]level_id:self.level_id];
    }else if (self.type == 2)
    {
        self.dataArray = [initd GetMainTableWithUpload_flag:1 typy_id:[self.param objectForKey:@"TYPE_ID"]level_id:self.level_id];
    }
    [self GetData];
    
    [self.tableview reloadData];
}
#pragma 通知的事件,执行刷新(夜查房)

- (void)RefreshNoticeHnight:(NSNotification *)sender
{
    [self.dataArray removeAllObjects];
    [self.titleArray removeAllObjects];
    InitDbTableQuality *initd = [[InitDbTableQuality alloc]init];
    if (self.type == 1) {
        self.dataArray = [initd GetMainTableWithUpload_flag:0 typy_id:[self.param objectForKey:@"TYPE_ID"]level_id:self.level_id];
    }else if (self.type == 2)
    {
        self.dataArray = [initd GetMainTableWithUpload_flag:1 typy_id:[self.param objectForKey:@"TYPE_ID"]level_id:self.level_id];
    }
    [self GetData];
    
    [self.tableview reloadData];
}



#pragma mark 获取源数据

- (void)GetData
{

    //对数据根据时间排序,时间最新的在前面
    NSArray *sortArray = [self.dataArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        
        Model_Hr_Ns_Inspect_New  *Model1 = obj1;
        Model_Hr_Ns_Inspect_New *Model2 = obj2;
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        
        [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
        
        NSDate *date1= [dateFormatter dateFromString:Model1.CHECK_DATE];
        NSDate *date2= [dateFormatter dateFromString:Model2.CHECK_DATE];
        
        if (date1 == [date1 earlierDate: date2]) { //不使用intValue比较无效
            
            return NSOrderedDescending;//降序
            
        }else if (date1 == [date1 laterDate: date2]) {
            return NSOrderedAscending;//升序
            
        }else{  
            return NSOrderedSame;//相等  
        }  
        
    }];
    
    NSMutableArray *array= [NSMutableArray arrayWithArray:sortArray];
    NSMutableArray *dateMutablearray = [NSMutableArray new];
    NSMutableArray *titleArray = [NSMutableArray new];
    for(int i = 0;i < array.count;i ++) {

        Model_Hr_Ns_Inspect_New*model = array[i];
        
        if (![titleArray containsObject:[model.CHECK_DATE substringToIndex:7]]) {
            [titleArray addObject:[model.CHECK_DATE substringToIndex:7]];
        }
        NSMutableArray*tempArray = [@[]mutableCopy];
        NSString *string = [model.CHECK_DATE substringToIndex:7];
        [tempArray addObject:model];
        
        for(int j = i+1;j < array.count;j ++) {
            
            Model_Hr_Ns_Inspect_New*model1 = array[j];
            NSString *jstring = [model1.CHECK_DATE substringToIndex:7];
            
            if([string isEqualToString:jstring]){
                
                [tempArray addObject:model1];
                
                
                [array removeObjectAtIndex:j];
                j -= 1;
                
            }
            
        }
        
        [dateMutablearray addObject:tempArray];
        
    }
    self.rowOfSectionArray = dateMutablearray;
    self.titleArray = titleArray;

}
- (UITableView *)tableview
{
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - NavBarHeight - 50) style:UITableViewStylePlain];
        _tableview.dataSource = self;
        _tableview.delegate = self;
        if (self.isHNight == 0) {
            [_tableview registerClass:[HUploadBaseTableViewCell class] forCellReuseIdentifier:@"cell"];
        }else {
            [_tableview registerClass:[HNightHistoryTableViewCell class] forCellReuseIdentifier:@"CELL"];

        }
        _tableview.tableFooterView = [[UIView alloc]init];
    }
    return _tableview;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
   return  self.titleArray.count;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return self.titleArray[section];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *array = self.rowOfSectionArray[section];
    return array.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isHNight == 0) {
        HUploadBaseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSArray *array = self.rowOfSectionArray[indexPath.section];
        Model_Hr_Ns_Inspect_New *model = array[indexPath.row];
        self.indexSection = indexPath.section;
        self.indexRow = indexPath.row;
        self.indexPath = indexPath;
        InitDbTableQuality *initd = [[InitDbTableQuality alloc]init];
        HQc_codeModel *codeModel = [initd GetCodeNameWithCodeID:model.CODE_ID];
        InitDbTable *inTabel = [[InitDbTable alloc]init];
        cell.code_nameLabel.text = codeModel.CODE_NAME;
        cell.check_dateLabel.text = [NSString stringWithFormat:@"%@",model.CHECK_DATE];
        cell.score_label.text = [NSString stringWithFormat:@"得分:%@",model.SCORE];
        cell.check_nameLabel.text = [NSString stringWithFormat:@"检查者:%@",model.CHECKER_NAME];
        HQc_deptModel *Model =  [inTabel GetQc_deptWithDept_id:model.DEPT_ID];
        cell.checkDepartLabel.text = [NSString stringWithFormat:@"%@",Model.DEPT_NAME];
        return cell;

    }else {
        HNightHistoryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSArray *array = self.rowOfSectionArray[indexPath.section];
        Model_Hr_Ns_Inspect_New *model = array[indexPath.row];
        self.indexSection = indexPath.section;
        self.indexRow = indexPath.row;
        self.indexPath = indexPath;
        InitDbTable *inTabel = [[InitDbTable alloc]init];
        NSArray *DicItemArray = [[[TablePubDictionaryItem alloc]init]getDictItemWithItemID:model.ROUND_HOURS];
        Model_Pub_Dictionary_Item *ItemModel = DicItemArray[0];
        self.modelItem = ItemModel.ITEM_NAME;
        HQc_deptModel *Model = [inTabel GetQc_deptWithDept_id:model.DEPT_ID];
        cell.checkDepartLabel.text = Model.DEPT_NAME;
        self.dept_name = Model.DEPT_NAME;
        cell.checkerLabel.text = [NSString stringWithFormat:@"检查者:%@",model.CHECKER_NAME];
        cell.nurseLabel.text = [NSString stringWithFormat:@"值班护士:%@",model.NURSE_NAME];
        cell.checkTimeInterLabel.text = [NSString stringWithFormat:@"检查时段:%@",ItemModel.ITEM_NAME?:@""];
        cell.checkDateLabel.text = model.CHECK_DATE;
        return cell;

    }
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    NSArray *array = self.rowOfSectionArray[indexPath.section];
    Model_Hr_Ns_Inspect_New *model = array[indexPath.row];
    InitDbTable* ins = [[InitDbTable alloc]init];
    [InitDbTable sharedFMDBManeger];
    NSMutableArray *detailArray = [ins Qc_codeDetail:model.TYPE_ID STANDARD_ID:model.STANDARD_ID par_id:model.CODE_ID];
    HSavedEditViewController *HSaveEditVC = [[HSavedEditViewController alloc]initWithDataArray:detailArray type:self.type level_id:self.level_id];
    HSaveEditVC.title = @"详细信息";
    HSaveEditVC.standard_id = model.STANDARD_ID;
    HSaveEditVC.result_id = model.RESULT_ID;
    
    HNightHistoryEditViewController *HNightEditVC = [[HNightHistoryEditViewController alloc]initWithIsUpload:self.type param:self.param];
    HNightEditVC.title = @"详细信息";
    HNightEditVC.standard_id = model.STANDARD_ID;
    HNightEditVC.result_id = model.RESULT_ID;
    HNightEditVC.ITEM_NAME = self.modelItem;
    HNightEditVC.dept_name = self.dept_name;
//    if (self.isHNight == 0) {
//        [self.navigationController pushViewController:HSaveEditVC animated:YES];
//
//    }else {
//        [self.navigationController pushViewController:HNightEditVC animated:YES];
//    }

}
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"是否确定删除?"
                                                        message:nil
                                                       delegate:nil
                                              cancelButtonTitle:@"取消"
                                              otherButtonTitles:@"确定", nil];
        [alert show];
        alert.tag = 200;
        alert.delegate = self;
        self.indexSection = indexPath.section;
        self.indexRow = indexPath.row;
        self.indexPath = indexPath;

        
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 200) {
        switch (buttonIndex) {
            case 0:{
                return;
            }
                break;
            case 1:{
                NSMutableArray *array = self.rowOfSectionArray[self.indexSection];
                Model_Hr_Ns_Inspect_New *model = array[self.indexRow];
                [array removeObjectAtIndex:self.indexRow];
                InitDbTableQuality *initd = [[InitDbTableQuality alloc]init];
                [initd deleteTableWithResult_id:model.RESULT_ID];
                [self.tableview deleteRowsAtIndexPaths:[NSArray arrayWithObject:self.indexPath] withRowAnimation:UITableViewRowAnimationFade];
            }
                break;
            default:
                break;
        }
    }
}
//点击上传之后 更新数据库中upload_flag = 1

- (void)updateUploadFlag
{
    if (self.rowOfSectionArray.count > 0 ) {
        NSMutableArray *array = self.rowOfSectionArray[self.indexSection];
        Model_Hr_Ns_Inspect_New *model = array[self.indexRow];
        InitDbTableQuality *initd = [[InitDbTableQuality alloc]init];
        [initd UpdateTableWithResult_id:model.RESULT_ID];

    }else {
        [HCommon popupSuccessMessage:@"无需上传的数据"];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
